/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package conexion;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import ral.Real;


/**
 *
 * @author Jaime Renato Castorela
 */
public class Conexion {
    public static String peticionGET(String url){
        HttpConnection hcon = null;
        DataInputStream dis = null;
        StringBuffer respuesta = new StringBuffer();
        try{
            hcon = ( HttpConnection )Connector.open( url );
            dis = new DataInputStream( hcon.openInputStream() );
            int c;
            while( (c = dis.read()) != -1 ){
                respuesta.append( (char)c );
            }
        }
        catch(Exception e){
            e.printStackTrace();
            respuesta.append( "" );

        }
        finally{
            try{
                if ( hcon != null ) hcon.close();
                if ( dis != null ) dis.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
            }
        }
        return respuesta.toString();
    }
    /**
     *@param url : La pagina web a la que se le hara la peticion, sin parametros
     *@param param : El nombre del parametro
     *@param valor : el valor del parametro
     *
     *
     */
    public static String peticionGETconParametro(String url, String param, int valor){
        HttpConnection hcon = null;
        DataInputStream dis = null;
        StringBuffer respuesta = new StringBuffer();
        url = url.concat("?"+param+"="+valor);
        System.out.println("Conectando a :"+url);
        try{

            hcon = ( HttpConnection )Connector.open( url );
            dis = new DataInputStream( hcon.openInputStream() );
            int c;
            while( (c = dis.read()) != -1 ){
                respuesta.append( (char)c );
            }
        }
        catch(Exception e){
            e.printStackTrace();
            respuesta.append( "" );

        }
        finally{
            try{
                if ( hcon != null ) hcon.close();
                if ( dis != null ) dis.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
            }
        }
        return respuesta.toString();
    }

    /*
     *Funcion hecha para los boletos
     */
    public static Image cargaImagen(String url,String param, String valor){
        HttpConnection hcon = null;
        DataInputStream dis = null;
        ByteArrayOutputStream bStrm = null;
        Image img = null;
        url = url.concat("?"+param+"="+valor);
        System.out.println("Conectando a :"+url);
        try{
            byte[] data;
            hcon = (HttpConnection) Connector.open(url);
            dis = hcon.openDataInputStream();
            int length = (int) hcon.getLength();
            if (length != -1){
                data = new byte[length];
                dis.readFully(data);
            }
            else{
                bStrm = new ByteArrayOutputStream();
                int ch;
                while ((ch = dis.read()) != -1)
                  bStrm.write(ch);
                data = bStrm.toByteArray();
                bStrm.close();
            }
            img =Image.createImage(data, 0, data.length);
         }catch(Exception e){
             e.printStackTrace();
         }
        finally{
            try{
                if ( hcon != null ) hcon.close();
                if ( dis != null ) dis.close();
                }catch(IOException ioe){
                    ioe.printStackTrace();
                }
            }
         return img;
    }
    
    /*
     * Funcion para obtener mapas
     *
     * @param width : ancho de la imagen
     * @param heigth : alto de la imagen
     * @param lng : longitud
     * @param lat : latitud
     * @param tipo : 0 = posicion, 1 = cine
     */
    public static Image ObtenerMapa(int width, int height, Real lat, Real lng, int tipo) throws IOException {

        String marker = "";
        if (tipo == 1) {
            marker = "color:blue|label:C|";
        } else if (tipo == 0) {
            marker = "color:red|label:P|";
        }
        byte[] imageData = loadHttpFile(getMapUrl(width, height, lng, lat, 16, marker));

        return Image.createImage(imageData, 0, imageData.length);
    }

    /*
     * Funcion para obtener url del mapa
     */
    private static String getMapUrl(int width, int height, Real lng, Real lat, int zoom, String marker) {
        return "http://maps.google.com/maps/api/staticmap?center=" + lat + "," + lng + "&format=png32"
                + "&zoom=" + zoom + "&size=" + width + "x" + height + "&markers=" + marker + lat
                + "," + lng + "&maptype=satellite&sensor=false";
    }

    /*
     * Función para obtener la imagen como arreglo de bytes
     */
    private static byte[] loadHttpFile(String url) throws IOException {
        byte[] byteBuffer;

        HttpConnection hc = (HttpConnection) Connector.open(url);
        try {
            hc.setRequestMethod(HttpConnection.GET);
            InputStream is = hc.openInputStream();
            try {
                int len = (int) hc.getLength();
                if (len > 0) {
                    byteBuffer = new byte[len];
                    int done = 0;
                    while (done < len) {
                        done += is.read(byteBuffer, done, len - done);
                    }
                } else {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[512];
                    int count;
                    while ( (count = is.read(buffer)) >= 0 ) {
                        bos.write(buffer, 0, count);
                    }
                    byteBuffer = bos.toByteArray();
                }
            } finally {
                is.close();
            }
        } finally {
            hc.close();
        }

        return byteBuffer;
    }
    
}
